package com.example.seakdreamandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.seakdreamandroid.entity.User;
import com.mob.MobSDK;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    //所需申请的权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.INTERNET,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_NETWORK_STATE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA
    };
    private static int count = 0;
    private LinearLayout loginByPassword;
    private LinearLayout loginByVerifyCode;
    private Button btnPassword;
    private Button btnVerifyCode;
    private TextView tvPassword;
    private TextView tvVerifyCode;
    EventHandler eventHandler;
    EditText editTextPhone,editTextNumber,passwordInput;
    Button get_code_id,login_id;
    Timer timer;
    int countT = 60;
    User user;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    /**
     * 冷岩
     */
    Handler handler = new Handler(Looper.getMainLooper()){
        public void handleMessage(Message msg) {
            int tag = msg.what;
            switch (tag){
                case 1:
                    int arg = msg.arg1;
                    if(arg==1){
                        get_code_id.setText("重新获取");//计时结束停止计时把值恢复
                        countT = 60;
                        timer.cancel();
                        get_code_id.setEnabled(true);
                    }else{
                        get_code_id.setText(countT+"");
                    }
                    break;
                case 2:
                    Toast.makeText(LoginActivity.this,"获取短信验证码成功",Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    Log.i("Codr","获取短信验证码失败");
                    Toast.makeText(LoginActivity.this,msg.getData().getString("code"),Toast.LENGTH_LONG).show();
                    //Toast.makeText(MainActivity.this,"获取短信验证码失败",Toast.LENGTH_LONG).show();
                    break;
                case 4:
                    if (msg.getData().getString("code").equals("登录成功！")){
                        upLoadByCode();
                    }
                    break;
                default:
                    break;
            }

        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        applyPermission();
        MobSDK.submitPolicyGrantResult(true,null);
        user = (User) getApplication();
        sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        //获取控件对象
        getViews();
        //设置控件的事件
        //setViewListener();
    }

    private void getViews() {
        tvPassword = findViewById(R.id.tv_password);
        tvVerifyCode = findViewById(R.id.tv_verifyCode);
        loginByVerifyCode = findViewById(R.id.login_verifyCode);
        loginByPassword = findViewById(R.id.login_password);
        btnVerifyCode = findViewById(R.id.btn_verifyCode);
        btnVerifyCode.setOnClickListener(this::onClick);
        btnPassword = findViewById(R.id.btn_password);
        btnPassword.setOnClickListener(this::onClick);

        editTextPhone = findViewById(R.id.editTextPhone);
        editTextNumber = findViewById(R.id.editTextNumber);
        get_code_id = findViewById(R.id.get_code_id);
        get_code_id.setOnClickListener(this::onClick);
        login_id = findViewById(R.id.login_id);
        login_id.setOnClickListener(this::onClick);
        passwordInput = findViewById(R.id.password_input);

        /**
         * 冷岩
         */
        eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {// TODO 此处为子线程！不可直接处理UI线程！处理后续操作需传到主线程中操作！
                Log.i("返回:",event+" | "+result+" | "+data.toString());
                if (result == SMSSDK.RESULT_COMPLETE) {//成功回调
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交短信、语音验证码成功
                        Bundle bundle = new Bundle();
                        bundle.putString("code","登录成功！");
                        Message message = new Message();
                        message.what = 4;
                        message.setData(bundle);
                        handler.sendMessage(message);
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    } else if (event == SMSSDK.EVENT_GET_VOICE_VERIFICATION_CODE) {//获取语音验证码成功
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                } else if (result == SMSSDK.RESULT_ERROR) {//失败回调
                    if(event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE){//提交返回
                        Bundle bundle = new Bundle();
                        bundle.putString("code","输入的验证码不正确！");
                        Message message = new Message();
                        message.what = 4;
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }else{
                        Bundle bundle = new Bundle();
                        bundle.putString("code",data.toString());
                        Message message = new Message();
                        message.what = 3;
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }

                } else {//其他失败回调
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
    }

    /**
     * 冷岩
     */
    //定义判断权限申请的函数，在onCreat中调用就行
    public void applyPermission(){
        if(Build.VERSION.SDK_INT>=23){
            boolean needApply=false;
            for(int i=0;i<PERMISSIONS_STORAGE.length;i++){
                int checkPermission= ContextCompat.checkSelfPermission(getApplicationContext(),
                        PERMISSIONS_STORAGE[i]);
                if(checkPermission!= PackageManager.PERMISSION_GRANTED){
                    needApply=true;
                }
            }
            if(needApply){
                ActivityCompat.requestPermissions(LoginActivity.this,PERMISSIONS_STORAGE,1);
            }
        }

    }

    /**
     * 冷岩
     */
    //重载用户是否同意权限的回调函数，进行相应处理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for(int i=0;i<grantResults.length;i++){      //检查权限是否获取
            if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
                //同意后的操作
                //Toast.makeText(MainActivity.this, permissions[i]+"已授权",Toast.LENGTH_SHORT).show();//提示
            }
            else {
                //不同意后的操作
                //Toast.makeText(MainActivity.this,permissions[i]+"拒绝授权",Toast.LENGTH_SHORT).show();//提示
            }
        }
    }

    //登陆逻辑
    private void upLoadByCode(){
        try {
            String phone = editTextPhone.getText().toString().trim();;
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
//                    .url("http://192.168.3.34:8080/UserInfo/queryUserByPhone?phone=" + phone)
                    .url(Constant.BASE_URL +  "UserInfo/queryUserByPhone?phone=" + phone)
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("okhttp", "请求失败");
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    try {
                        JSONObject result = new JSONObject(str);
                        if (result.getString("code").equals("404")){
                            Intent intent = new Intent();
                            intent.setClass(LoginActivity.this, SetPasswordActivity.class);
                            intent.putExtra("phone", phone);
                            startActivity(intent);
                        }else if (result.getString("code").equals("200")){
                            Intent intent = new Intent();
                            intent.setClass(LoginActivity.this, MainActivity.class);
                            JSONObject userInfo = result.getJSONObject("data");
//                            intent.putExtra("userId", userInfo.getString("userId"));
                            editor.putString("token", result.getString("token"));
                            editor.commit();
                            user.setUserId(userInfo.getString("userId"));
                            user.setIf_vip(userInfo.getString("ifVip"));
                            user.setPoints(userInfo.getInt("points"));
                            startActivity(intent);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void upLoadByPassword(){
        try {
            String phone = editTextPhone.getText().toString().trim();;
            String password = passwordInput.getText().toString().trim();
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody requestBody = new FormBody.Builder()
                    .add("phone", phone)
                    .add("password", password)
                    .build();
            Request request = new Request.Builder()
                    .url(Constant.BASE_URL + "UserInfo/login")
                    .post(requestBody)
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("okhttp", "请求失败");
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    try {
                        JSONObject result = new JSONObject(str);
                        if (result.getString("code").equals("404")){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //显示
                                    Toast.makeText(LoginActivity.this,"首次登录请使用验证码登录",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }else if (result.getString("code").equals("200")){
                            JSONObject userInfo = result.getJSONObject("data");
                            Log.i("adadad", result.getString("token"));
                            editor.putString("token", result.getString("token"));
                            editor.commit();
                            Intent intent = new Intent();
                            intent.setClass(LoginActivity.this, MainActivity.class);
                            user.setUserId(userInfo.getString("userId"));
                            user.setIf_vip(userInfo.getString("ifVip"));
                            user.setPoints(userInfo.getInt("points"));
                            startActivity(intent);
//                            if (password.equals(userInfo.getString("password"))){
//                                Intent intent = new Intent();
//                                intent.setClass(LoginActivity.this, MainActivity.class);
////                                intent.putExtra("userId", userInfo.getString("userId"));
//                                user.setUserId(userInfo.getString("userId"));
//                                startActivity(intent);
//                            }else{
//                                Toast.makeText(LoginActivity.this,"密码错误",Toast.LENGTH_SHORT).show();
//                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 冷岩
     */
    private void onClick(View view) {
        String phone = "";
        String code = "";
        String password = "";
        int id = view.getId();
        switch (id){
            case R.id.get_code_id:

                phone = editTextPhone.getText().toString().trim();
                if (!TextUtils.isEmpty(phone)){//倒计时
                    CountdownStart();
                    getVerificationCode("86",phone);
                }else{
                    Toast.makeText(this,"请输入手机号码",Toast.LENGTH_LONG).show();
                }
                break;
            //登录
            case R.id.login_id:

                phone = editTextPhone.getText().toString().trim();;
                code = editTextNumber.getText().toString().trim();
                password = passwordInput.getText().toString().trim();
                if (tvPassword.getVisibility() == View.VISIBLE){
                    if (TextUtils.isEmpty(phone)){
                        Toast.makeText(this,"请输入手机号码",Toast.LENGTH_LONG).show();
                    }else if (TextUtils.isEmpty(password)){
                        Toast.makeText(this,"请输入密码",Toast.LENGTH_LONG).show();
                    }else{
                        //登录逻辑
                        upLoadByPassword();
                    }
                }else{
                    if (TextUtils.isEmpty(phone)){
                        Toast.makeText(this,"请输入手机号码",Toast.LENGTH_LONG).show();
                    }else if (TextUtils.isEmpty(code)){
                        Toast.makeText(this,"请输入验证码",Toast.LENGTH_LONG).show();
                    }else{//登录逻辑
                        /**
                         * cn.smssdk.SMSSDK.class
                         * 提交验证码
                         * @param country   国家区号
                         * @param phone     手机号
                         * @param code      验证码
                         */
                        SMSSDK.submitVerificationCode("86",phone,code);//提交验证码
                    }
                }
                break;
            case R.id.btn_password:
                //显示密码登录标题
                tvPassword.setVisibility( View.VISIBLE );
                //显示密码登录输入框
                loginByPassword.setVisibility( View.VISIBLE );
                //显示按钮 短信验证码登录
                btnVerifyCode.setVisibility( View.VISIBLE );
                //隐藏验证码登录标题
                tvVerifyCode.setVisibility( View.GONE );
                //隐藏短信验证码输入框
                loginByVerifyCode.setVisibility( View.GONE );
                //隐藏按钮 密码的登录
                btnPassword.setVisibility( View.GONE );
                break;
            case R.id.btn_verifyCode:
                //显示验证码登录标题
                tvVerifyCode.setVisibility( View.VISIBLE );
                //显示验证码登录输入框
                loginByVerifyCode.setVisibility( View.VISIBLE );
                //显示按钮 密码登录
                btnPassword.setVisibility( View.VISIBLE );
                //隐藏密码登录标题
                tvPassword.setVisibility( View.GONE );
                //隐藏密码输入框
                loginByPassword.setVisibility( View.GONE );
                //隐藏按钮 验证码的登录
                btnVerifyCode.setVisibility( View.GONE );
                break;
        }
    }

    /**
     * cn.smssdk.SMSSDK.class
     * 请求文本验证码
     * @param country   国家区号
     * @param phone     手机号
     * 冷岩
     */
    public static void getVerificationCode(String country, String phone){
        //获取短信验证码
        SMSSDK.getVerificationCode(country,phone);
    }

    /**
     * 冷岩
     */
    //倒计时函数
    private void CountdownStart(){
        get_code_id.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                message.arg1 = countT;
                if(countT!=0){
                    countT--;
                }else {
                    return;
                }
                handler.sendMessage(message);
            }
        }, 1000,1000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();// 使用完EventHandler需注销，否则可能出现内存泄漏
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}